package com.ocl.www.filter;

/**
 * Created by Administrator on 2016/12/8.
 */
import com.ocl.www.security.ShiroCasConfiguration;
import com.ocl.www.utils.ResourceBundleUtils;
import com.ocl.www.utils.UserUntil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 使用注解标注过滤器
 * @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器
 * 属性filterName声明过滤器的名称,可选
 * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
 *
 * @author   单红宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2016年1月6日
 */
@WebFilter(filterName="myFilter",urlPatterns="/swagger-ui.html")
public class MyFilter implements Filter {


    private Logger log = Logger.getLogger(MyFilter.class);
    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        System.out.println("======执行过滤操作=======");
        int userId;
        try {
            userId = UserUntil.getUserId(SecurityUtils.getSubject().getPrincipals().asSet());

            Subject subject = SecurityUtils.getSubject();
            boolean isPermitted = subject.isPermitted("查看API文档");
			if(isPermitted == true) {
				log.info("该用户拥有此权限：查看API文档");
                chain.doFilter(request, response);
			}else{
				log.info("该用户没有此权限：查看API文档");
                resp.sendRedirect(ResourceBundleUtils.getProperty("project.page.host")+"/403.html");

			}
        }catch(NullPointerException e){
            log.info("用户尚未登录！");
            resp.sendRedirect(ShiroCasConfiguration.loginUrl);
            //resp.sendRedirect("http://192.168.1.39/cas-server-webapp/login?service=http://192.168.1.39/ocl-server/shiro-cas");
//          chain.doFilter(request,response);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器初始化");
    }

}
